package com.lujianfei.powersearch.logger.impl;

import android.util.Log;


import com.lujianfei.powersearch.logger.Logger;

import java.util.Locale;

/**
 * 描述:
 * 创建者: lujianfei
 * 日期: 2025/5/20
 */

public class AndroidLogger implements Logger {
    @Override
    public void d(String tag, String msg) {
        print(tag, msg, LogLevel.Debug);
    }

    @Override
    public void e(String tag, String msg, Throwable e) {
        print(tag, msg, LogLevel.Error);
        if (e != null) {
            Log.e(tag, "Exception: ", e);
        }
    }

    @Override
    public void i(String tag, String msg) {
        print(tag, msg, LogLevel.Info);
    }

    @Override
    public void v(String tag, String msg) {
        print(tag, msg, LogLevel.Info);
    }

    @Override
    public void w(String tag, String msg) {
        print(tag, msg, LogLevel.Warning);
    }

    @Override
    public void wtf(String tag, String msg) {
        print(tag, msg, LogLevel.Warning);
    }

    private enum LogLevel {
        Info, Warning, Debug, Error
    }

    private void print(String tag, String msg, LogLevel level) {
        int index = 4;
        StringBuilder stringBuffer = new StringBuilder();
        // 打印栈帧中的所有方法调用
        try {
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            String className = stackTrace[index].getFileName();
            String methodName = stackTrace[index].getMethodName();
            int lineNumber = stackTrace[index].getLineNumber();
            methodName = methodName.substring(0, 1).toUpperCase(Locale.getDefault())
                    + methodName.substring(1);
            stringBuffer.append("[(")
                    .append(className).append(":").append(lineNumber).append(")#")
                    .append(methodName).append("] ");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String finalMsg = stringBuffer.toString() + ": " + msg;
        switch (level) {
            case Info:
                Log.i(tag, finalMsg);
                break;
            case Warning:
                Log.w(tag, finalMsg);
                break;
            case Debug:
                Log.d(tag, finalMsg);
                break;
            case Error:
                Log.e(tag, finalMsg);
                break;
        }
    }
}
